<template>
  <el-drawer title="详细信息" v-model="Visible" size="40%" :before-close="closeDrawer">
    <el-form ref="formRef" :inline="true" :model="item" class="form-inline" :rules="allRules"
             label-width="auto">
      <div>
        <el-form-item label="状态" prop="orderStatus">
          <el-select v-model="item.orderStatus" style="width: 200px;">
            <el-option v-for="item in getEnumBySn('orderStatus')" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作编号" prop="indexId">
          <el-select v-model="item.indexId" clearable filterable placeholder="选择中介"
                     style="width: 200px;">
            <el-option v-for="item in EnumB" :key="item.indexId" :label="item.agencyName"
                       :value="item.indexId"/>
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="客户姓名" prop="customName">
          <el-input v-model="item.customName" required style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="item.sex" required style="width: 200px;" @change="sexChange">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

      </div>
      <div>
        <el-form-item label="接单日期" prop="orderReceiveDate">
          <el-date-picker type="datetime" v-model="item.orderReceiveDate"
                          value-format="YYYY-MM-DD HH:mm:ss"

                          placeholder="接单日期" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker type="datetime" v-model="item.orderEndDate"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          @change="orderReceiveDateChangeHandle"
                          placeholder="结束日期" style="width: 200px;"/>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="item.businessType" required style="width: 200px;"
                     @change="businessTypeHandle">
            <el-option v-for="item in getEnumBySn('businessType')" :label="item.label"
                       :key="item.value"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="托管类型" prop="trusteeshipType">
          <el-select v-model="item.trusteeshipType" required style="width: 200px;" clearable>
            <el-option v-for="item in getEnumBySn('cycleTypeEnum')" :label="item.label"
                       :key="item.value"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>

      </div>

      <div>
        <el-form-item label="转接手机号" prop="transferPhone">
          <el-select v-model="item.transferPhone" clearable filterable placeholder=""
                     style="width: 200px;">
            <el-option v-for="item in currentTransferPhone" :key="item.id" :label="item.indexId"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="籍贯">
          <el-input v-model="item.nativePlace" required style="width: 200px;"></el-input>
        </el-form-item>


      </div>
      <div>
        <el-form-item label="缴费提醒日期">
          <el-date-picker type="datetime" v-model="item.reminderTime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="缴费提醒日期" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="有无尾款" prop="balancePayment">
          <el-select v-model="item.balancePayment" style="width: 200px;" clearable>
            <el-option v-for="item in getEnumBySn('balancePayment')" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

      </div>

      <div style="width: 100%;">
        <el-form-item label="平台备注" prop="platformMemo" style="width: 100%;">
          <el-input type="" v-model="item.platformMemo" style="width: 100%;"></el-input>
        </el-form-item>
      </div>

      <div style="width: 100%;">
        <el-form-item label="备注" style="width: 100%;">
          <el-input type="textarea" v-model="item.memo" required style="width: 100%;" :rows="10" :autosize="{ minRows: 10, maxRows: 10 }"></el-input>
        </el-form-item>
      </div>

    </el-form>
    <div class="drawer-footer">
      <div style="display: flex; justify-content: space-between; width: 100%;">
        <el-button @click="closeDrawer" style="width: 50%;height: 60px;font-size: 60px;">取消</el-button>
        <el-button style="width: 50%;height: 60px;font-size: 60px;" type="primary" size="large" @click="saveItem">保存</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import {ref, defineEmits, watch, onMounted} from 'vue';
import {getEnumBySn} from "@/api/enums";

const props = defineProps({
  drawerVisible: {
    type: Boolean,
    required: true,
  },
  currentItem: {
    type: Object,
    required: true,
  },
  EnumA: {
    type: Array,
    required: true,
  },
  EnumB: {
    type: Array,
    required: true,
  },
});
const formRef = ref();


const baseRules = ref({
  sex: [{required: true, message: '请选择性别', trigger: 'blur'}],
  orderReceiveDate: [{required: true, message: '请选择接单起始日期', trigger: 'blur'}],
  businessType: [{required: true, message: '请选择业务类型', trigger: 'blur'}],
  indexId: [{required: true, message: '请选择合作编号', trigger: 'blur'}],
  orderStatus: [{required: true, message: '请选择状态', trigger: 'blur'}],
  customName: [{required: true, message: '请输入客户姓名', trigger: 'blur'}],
  balancePayment: [{required: true, message: '请选择有无尾款', trigger: 'blur'}],
  transferPhone: [{required: true, message: '请选择转接手机号', trigger: 'blur'}],
})

const trusteeshipTypeRules = ref({
  trusteeshipType: [{required: true, message: '请选择托管类型', trigger: 'blur'}],
})

const platformMemoRules = ref({
  trusteeshipType: [{required: true, message: '请选择托管类型', trigger: 'blur'}],
  platformMemo: [{required: true, message: '请输入平台备注', trigger: 'blur'}],
})


const allRules = ref({...baseRules.value})

const businessTypeHandle = function () {
  if (item.value?.businessType === '托管') {
    allRules.value = {...baseRules.value, ...trusteeshipTypeRules.value}
  } else if (item.value?.businessType === '托管特殊') {
    console.log('托管特殊')
    allRules.value = {...baseRules.value, ...platformMemoRules.value}
  } else {
    allRules.value = {...baseRules.value}
  }
}

const currentTransferPhone = ref([]);
const sexChange = function () {
  currentTransferPhone.value = props.EnumA.filter((current) => {
    return current && current.indexId.includes(item.value?.sex);
  });
}


const Visible = ref(true);
const item = ref({});

const emit = defineEmits(['close', 'save']);
onMounted(() => {
  item.value = props.currentItem
  businessTypeHandle()
});
watch(() => props.drawerVisible, (newVal) => {
  if (!newVal) {
    resetForm();
  }
});

function resetForm() {
  // 重置表单（如果需要）
}

function closeDrawer() {
  emit('close');
}

onMounted(() => {
  currentTransferPhone.value = props.EnumA.filter((current) => {
    return current && current.indexId?.includes(item.value?.sex);
  });
})

const orderReceiveDateChangeHandle = function (newValue) {
  if (!newValue) {
    return
  }
  // 解析输入的日期字符串
  const [datePart, timePart] = newValue.split(' ');
  const [year, month, day] = datePart.split('-').map(Number);
  const [hours, minutes, seconds] = timePart.split(':').map(Number);

  // 创建一个 UTC 日期对象
  const date = new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)); // month - 1 因为 JavaScript 中月份从 0 开始

  // 减去一天
  date.setUTCDate(date.getUTCDate() - 1);

  // 格式化输出为 yyyy-MM-dd hh:mm:ss
  const formattedDate = date.toISOString().replace('T', ' ').substring(0, 19);

  item.value.reminderTime = formattedDate;
}

const saveItem = async function () {
  await formRef.value?.validate().then((valid) => {
    if (!valid) {
      return
    }
  })
  emit('save', item);
}
</script>

<style scoped>
.drawer-footer {
  padding: 20px;
  width: 100%;
}

.drawer-footer .el-button {
  min-width: 120px;
  height: 40px;
  font-size: 16px;
}

.item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.select,
.input {
  margin-right: 10px;
  width: 200px;
  /* 调整宽度以适应布局 */
}

.delete-button {
  margin-left: 10px;
}

.add-button {
  margin-bottom: 10px;
}
</style>
